<template>
  <el-dialog
    v-model="visible"
    :show-close="false"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    width="680px"
    align-center
    class="global-search-dialog"
    @closed="handleClosed"
  >
    <template #header>
      <div class="search-header">
        <el-icon class="search-icon"><Search /></el-icon>
        <input
          ref="searchInputRef"
          v-model="searchKeyword"
          type="text"
          placeholder="搜索功能、页面、快捷方式..."
          class="search-input"
          autofocus
          @keydown.down.prevent="handleArrowDown"
          @keydown.up.prevent="handleArrowUp"
          @keydown.enter="handleEnter"
          @keydown.esc="visible = false"
        />
        <el-button text @click="visible = false">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </template>

    <div class="search-content">
      <!-- 搜索结果 -->
      <div v-if="searchKeyword && filteredResults.length > 0" class="search-results">
        <el-scrollbar max-height="450px">
          <div
            v-for="(item, index) in filteredResults"
            :key="item.path"
            class="search-result-item"
            :class="{ active: selectedIndex === index }"
            @click="handleSelectItem(item)"
            @mouseenter="selectedIndex = index"
          >
            <div class="result-icon" :style="{ background: item.gradient || item.color }">
              <el-icon :size="20">
                <component :is="item.icon" />
              </el-icon>
            </div>
            <div class="result-info">
              <div class="result-title">
                <span v-html="highlightText(item.title)"></span>
                <el-tag v-if="item.badge" :type="getBadgeType(item.badge)" size="small" class="result-badge">
                  {{ item.badge }}
                </el-tag>
              </div>
              <div class="result-desc">
                <span class="result-module">{{ item.module }}</span>
                <span v-if="item.description" class="result-description">{{ item.description }}</span>
              </div>
            </div>
            <div class="result-path">
              {{ item.path }}
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 搜索为空时显示 -->
      <div v-else-if="searchKeyword && filteredResults.length === 0" class="search-empty">
        <el-icon :size="48" color="#909399"><DocumentDelete /></el-icon>
        <p>未找到 "{{ searchKeyword }}" 相关的功能</p>
        <small>尝试使用其他关键词搜索</small>
      </div>

      <!-- 默认显示最近访问和快捷方式 -->
      <div v-else class="search-default">
        <el-scrollbar max-height="420px" class="default-scrollbar">
          <div class="default-content">
            <!-- 快捷方式 -->
            <div v-if="quickAccess.length > 0" class="default-section">
              <div class="section-title">
                <el-icon><Star /></el-icon>
                快捷方式
              </div>
              <div class="quick-access-grid">
                <div
                  v-for="item in quickAccess"
                  :key="item.path"
                  class="quick-access-item"
                  @click="handleSelectItem(item)"
                >
                  <div class="quick-icon" :style="{ background: item.gradient || item.color }">
                    <el-icon :size="20">
                      <component :is="item.icon" />
                    </el-icon>
                  </div>
                  <div class="quick-title">{{ item.title }}</div>
                </div>
              </div>
            </div>

            <!-- 最近访问 -->
            <div v-if="recentItems.length > 0" class="default-section">
              <div class="section-title">
                <el-icon><Clock /></el-icon>
                最近访问
                <el-button 
                  size="small" 
                  text 
                  type="danger" 
                  @click="handleClearHistory"
                  style="margin-left: auto;"
                >
                  <el-icon><Delete /></el-icon>
                  清空
                </el-button>
              </div>
              <div class="recent-list">
                <div
                  v-for="item in recentItems"
                  :key="item.path"
                  class="recent-item"
                  @click="handleSelectItem(item)"
                >
                  <el-icon :size="16" :color="item.color">
                    <component :is="item.icon" />
                  </el-icon>
                  <span class="recent-title">{{ item.title }}</span>
                  <span class="recent-time">{{ item.time }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>

        <!-- 快捷键提示 -->
        <div class="shortcuts-tips">
          <div class="tip-item">
            <kbd>↑</kbd> <kbd>↓</kbd> 选择
          </div>
          <div class="tip-item">
            <kbd>Enter</kbd> 打开
          </div>
          <div class="tip-item">
            <kbd>Esc</kbd> 关闭
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { menuData } from '@/config/menu'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { getVisitHistory, clearVisitHistory } from '@/utils/visitHistory'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const router = useRouter()
const route = useRoute()

// 响应式数据
const searchKeyword = ref('')
const selectedIndex = ref(0)
const searchInputRef = ref(null)

// 可见性控制
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 构建所有可搜索的菜单项
const allMenuItems = computed(() => {
  const items = []
  const addedPaths = new Set() // 防止重复添加
  
  const traverse = (menus, parentModule = '', level = 1) => {
    menus.forEach(menu => {
      // 确定当前模块名称
      let currentModule = parentModule
      if (level === 1 && menu.children && menu.children.length > 0) {
        // 第一层有子菜单的，作为模块名
        currentModule = menu.title
      }
      
      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        traverse(menu.children, currentModule, level + 1)
      }
      
      // 添加可访问的菜单项到搜索列表
      // 条件：有路径 且 (没有子菜单 或 路径段数>=3)
      if (menu.path && !addedPaths.has(menu.path)) {
        const pathSegments = menu.path.split('/').filter(s => s)
        const shouldAdd = !menu.children || pathSegments.length >= 2
        
        if (shouldAdd && currentModule) {
          items.push({
            title: menu.title,
            path: menu.path,
            icon: markRaw(ElementPlusIconsVue[menu.icon] || ElementPlusIconsVue.Document),
            module: currentModule,
            badge: menu.badge || '',
            description: menu.description || '',
            color: getModuleColor(currentModule),
            gradient: getModuleGradient(currentModule)
          })
          addedPaths.add(menu.path)
        }
      }
    })
  }
  
  traverse(menuData)
  
  console.log('全局搜索：已加载', items.length, '个功能')
  return items
})

// 过滤搜索结果
const filteredResults = computed(() => {
  if (!searchKeyword.value) return []
  
  const keyword = searchKeyword.value.toLowerCase()
  
  return allMenuItems.value.filter(item => {
    return item.title.toLowerCase().includes(keyword) ||
           item.path.toLowerCase().includes(keyword) ||
           item.module.toLowerCase().includes(keyword) ||
           (item.description && item.description.toLowerCase().includes(keyword))
  }).slice(0, 20) // 限制最多显示20条
})

// 快捷访问（常用功能）
const quickAccess = ref([
  {
    title: '工作台',
    path: '/dashboard',
    icon: markRaw(ElementPlusIconsVue.Monitor),
    module: '首页',
    color: '#409EFF',
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    title: '销售订单',
    path: '/sales/orders',
    icon: markRaw(ElementPlusIconsVue.Document),
    module: '销售管理',
    color: '#67C23A',
    gradient: 'linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%)'
  },
  {
    title: '商品管理',
    path: '/inventory/products',
    icon: markRaw(ElementPlusIconsVue.Goods),
    module: '库存管理',
    color: '#E6A23C',
    gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
  },
  {
    title: '会员资料',
    path: '/member/members',
    icon: markRaw(ElementPlusIconsVue.User),
    module: '会员管理',
    color: '#F56C6C',
    gradient: 'linear-gradient(135deg, #f77062 0%, #fe5196 100%)'
  },
  {
    title: '采购订单',
    path: '/purchase/orders',
    icon: markRaw(ElementPlusIconsVue.ShoppingBag),
    module: '采购管理',
    color: '#909399',
    gradient: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)'
  },
  {
    title: '报表中心',
    path: '/reports',
    icon: markRaw(ElementPlusIconsVue.DataBoard),
    module: '综合报表',
    color: '#606266',
    gradient: 'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)'
  }
])

// 历史记录刷新触发器
const historyRefreshKey = ref(0)

// 最近访问（从 localStorage 读取）
const recentItems = computed(() => {
  // 使用 historyRefreshKey 来触发重新计算
  historyRefreshKey.value
  
  try {
    const recent = getVisitHistory(8)
    return recent.map(item => ({
      ...item,
      icon: markRaw(ElementPlusIconsVue[item.iconName] || ElementPlusIconsVue.Document)
    }))
  } catch (error) {
    console.error('获取访问历史失败:', error)
    return []
  }
})

// 高亮搜索关键词
const highlightText = (text) => {
  if (!searchKeyword.value) return text
  const regex = new RegExp(`(${searchKeyword.value})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}

// 获取徽章类型
const getBadgeType = (badge) => {
  const typeMap = {
    'NEW': 'success',
    'HOT': 'danger',
    'AI': 'warning'
  }
  return typeMap[badge] || 'info'
}

// 获取模块颜色
const getModuleColor = (module) => {
  const colorMap = {
    '工作台': '#667eea',
    '销售管理': '#84fab0',
    '采购管理': '#a8edea',
    '库存管理': '#fa709a',
    '财务管理': '#fccb90',
    '会员管理': '#f77062',
    '报表中心': '#e0c3fc',
    '系统管理': '#c471f5'
  }
  return colorMap[module] || '#409EFF'
}

// 获取模块渐变色
const getModuleGradient = (module) => {
  const gradientMap = {
    '工作台': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    '销售管理': 'linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%)',
    '采购管理': 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
    '库存管理': 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    '财务管理': 'linear-gradient(135deg, #fccb90 0%, #d57eeb 100%)',
    '会员管理': 'linear-gradient(135deg, #f77062 0%, #fe5196 100%)',
    '报表中心': 'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)',
    '系统管理': 'linear-gradient(135deg, #c471f5 0%, #fa71cd 100%)'
  }
  return gradientMap[module] || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
}

// 键盘导航
const handleArrowDown = () => {
  if (filteredResults.value.length === 0) return
  selectedIndex.value = (selectedIndex.value + 1) % filteredResults.value.length
}

const handleArrowUp = () => {
  if (filteredResults.value.length === 0) return
  selectedIndex.value = (selectedIndex.value - 1 + filteredResults.value.length) % filteredResults.value.length
}

const handleEnter = () => {
  if (filteredResults.value.length > 0) {
    handleSelectItem(filteredResults.value[selectedIndex.value])
  }
}

// 选择项目
const handleSelectItem = (item) => {
  if (!item || !item.path) return
  
  // 跳转（路由守卫会自动记录访问历史）
  router.push(item.path)
  visible.value = false
  ElMessage.success(`正在打开 ${item.title}`)
}

// 清空访问历史
const handleClearHistory = () => {
  ElMessageBox.confirm(
    '确定要清空所有访问历史吗？此操作不可恢复。',
    '清空历史记录',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const success = clearVisitHistory()
    if (success) {
      ElMessage.success('访问历史已清空')
      // 触发刷新
      historyRefreshKey.value++
    } else {
      ElMessage.error('清空失败，请重试')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 对话框关闭时重置
const handleClosed = () => {
  searchKeyword.value = ''
  selectedIndex.value = 0
}

// 监听对话框打开，聚焦输入框
watch(visible, (newVal) => {
  if (newVal) {
    // 刷新历史记录
    historyRefreshKey.value++
    
    nextTick(() => {
      searchInputRef.value?.focus()
    })
  }
})
</script>

<style scoped>
.global-search-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.2);
}

.global-search-dialog :deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
}

.global-search-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  gap: 12px;
}

.search-icon {
  font-size: 20px;
  color: #909399;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  color: #303133;
  background: transparent;
}

.search-input::placeholder {
  color: #c0c4cc;
}

.search-content {
  min-height: 200px;
  max-height: 500px;
}

/* 搜索结果 */
.search-results {
  padding: 8px 0;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-result-item:hover,
.search-result-item.active {
  background: #f5f7fa;
}

.result-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.result-info {
  flex: 1;
  min-width: 0;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.result-title :deep(.highlight) {
  color: #409eff;
  font-weight: 600;
  background: rgba(64, 158, 255, 0.1);
  padding: 0 2px;
  border-radius: 2px;
}

.result-badge {
  font-size: 10px;
  padding: 0 4px;
  height: 16px;
  line-height: 16px;
}

.result-desc {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-module {
  color: #606266;
}

.result-description {
  color: #c0c4cc;
}

.result-path {
  font-size: 12px;
  color: #c0c4cc;
  font-family: monospace;
  flex-shrink: 0;
}

/* 空状态 */
.search-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.search-empty p {
  margin: 16px 0 8px;
  font-size: 14px;
  color: #606266;
}

.search-empty small {
  font-size: 12px;
  color: #c0c4cc;
}

/* 默认显示 */
.search-default {
  display: flex;
  flex-direction: column;
}

.default-scrollbar {
  flex: 1;
}

.default-content {
  padding: 16px 20px;
}

.default-section {
  margin-bottom: 24px;
}

.default-section:last-of-type {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
}

/* 快捷访问网格 */
.quick-access-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.quick-access-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.2s;
}

.quick-access-item:hover {
  border-color: #409eff;
  background: #f5f7fa;
  transform: translateY(-2px);
}

.quick-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.quick-title {
  font-size: 13px;
  color: #303133;
  font-weight: 500;
  text-align: center;
}

/* 最近访问列表 */
.recent-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-right: 4px; /* 为滚动条留出空间 */
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.recent-item:hover {
  background: #f5f7fa;
}

.recent-title {
  flex: 1;
  font-size: 13px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.recent-time {
  font-size: 12px;
  color: #c0c4cc;
  flex-shrink: 0;
}

/* 滚动条样式优化 */
.search-default :deep(.el-scrollbar__bar) {
  opacity: 0.6;
}

.search-default :deep(.el-scrollbar__bar:hover) {
  opacity: 1;
}

.search-results :deep(.el-scrollbar__bar) {
  opacity: 0.6;
}

.search-results :deep(.el-scrollbar__bar:hover) {
  opacity: 1;
}

/* 快捷键提示 */
.shortcuts-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;
  padding: 12px 16px;
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
  flex-shrink: 0;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
}

kbd {
  padding: 2px 6px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 11px;
  font-family: monospace;
  color: #606266;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
</style>

